package com.store.controller;

import com.store.common.Result;
import com.store.dto.OrderDTO;
import com.store.dto.request.ProductRequest;
import com.store.entity.Product;
import com.store.service.OrderService;
import com.store.service.ProductService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderService orderService;

    @GetMapping
    public Result<List<Product>> getList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId) {
        return Result.success(productService.getList(page, pageSize, keyword, categoryId));
    }

    @GetMapping("/{id}")
    public Result<Product> getById(@PathVariable Long id) {
        return Result.success(productService.findById(id));
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Product> create(@RequestBody ProductRequest request) {
        return Result.success(productService.create(request));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Product> update(@PathVariable Long id, @RequestBody ProductRequest request) {
        return Result.success(productService.update(id, request));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> delete(@PathVariable Long id) {
        productService.delete(id);
        return Result.success();
    }

    @GetMapping("/category/{categoryId}")
    public Result<List<Product>> getByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return Result.success(productService.getByCategory(categoryId, page, pageSize));
    }

    @GetMapping("/search")
    public Result<List<Product>> search(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return Result.success(productService.search(keyword, page, pageSize));
    }

    @PutMapping("/{id}/stock")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> updateStock(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> stockData) {
        Integer stock = stockData.get("stock");
        productService.updateStock(id, stock);
        return Result.success();
    }

    @PostMapping("/{id}/purchase")
    public Result<OrderDTO> purchaseProduct(@PathVariable Long id, @RequestBody PurchaseRequest request) {
        // 获取当前登录用户
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || "anonymousUser".equals(auth.getPrincipal())) {
            return Result.error(401, "请先登录");
        }
        
        // Extract user ID from the principal object
        Object principal = auth.getPrincipal();
        Long userId;
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            // If using Spring Security's User class
            userId = Long.parseLong(((org.springframework.security.core.userdetails.User) principal).getUsername());
        } else if (principal instanceof com.store.entity.User) {
            // If using our custom User entity
            userId = ((com.store.entity.User) principal).getId();
        } else {
            return Result.error(401, "无效的用户信息");
        }

        // 获取商品信息
        Product product = productService.findById(id);
        if (product == null) {
            return Result.error(404, "商品不存在");
        }

        // 检查库存
        if (product.getStock() < request.getQuantity()) {
            return Result.error(400, "库存不足");
        }

        // 创建订单
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(userId);
        orderDTO.setProductId(product.getProductId());
        orderDTO.setProductName(product.getProductName());
        orderDTO.setProductPrice(product.getProductPrice());
        orderDTO.setQuantity(request.getQuantity());
        orderDTO.setShippingAddress(request.getShippingAddress());
        orderDTO.setShippingName(request.getShippingName());
        orderDTO.setShippingPhone(request.getShippingPhone());

        // 保存订单
        OrderDTO createdOrder = orderService.createOrder(orderDTO);

        // 更新商品库存
        productService.updateStock(id, product.getStock() - request.getQuantity());

        return Result.success(createdOrder);
    }
}

@Data
class PurchaseRequest {
    private Integer quantity;           // 购买数量
    private String shippingAddress;     // 收货地址
    private String shippingName;        // 收货人姓名
    private String shippingPhone;       // 收货人电话
} 